package com.aizuda.boot.modules.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis 工具类，支持基本缓存、集合、分布式锁功能
 */
@Slf4j
@Service
public class RedisService {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     *
     * @param key
     * @param hKey
     */
    public void delCacheMapValue(final String key, final String hKey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }

    // ========== 分布式锁 ==========

    private static final long DEFAULT_WAIT_MS = 3000;
    private static final long DEFAULT_INTERVAL_MS = 100;
    private static final long DEFAULT_EXPIRE_MS = 5000;

    // 每个线程的锁 key -> value 映射
    private final ThreadLocal<Map<String, String>> lockMapThreadLocal = ThreadLocal.withInitial(HashMap::new);

    /**
     * 获取锁（默认参数）
     */
    public boolean tryLock(String key) {
        return tryLock(key, DEFAULT_WAIT_MS, DEFAULT_INTERVAL_MS, DEFAULT_EXPIRE_MS);
    }

    /**
     * 获取锁
     * @param key
     * @param waitTimeMs 等待时间 (毫秒) ,在这个时间内会多次尝试获取锁，超过这个时间还没获得锁，就返回false
     * @param intervalMs 间隔时间 (毫秒),每隔多长时间尝试一次获的锁
     * @param expireTimeMs 过期时间 (毫秒) key的过期时间
     * @return
     */
    public boolean tryLock(String key, long waitTimeMs, long intervalMs, long expireTimeMs) {
        String value = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        long endTime = System.currentTimeMillis() + waitTimeMs;

        while (System.currentTimeMillis() < endTime) {
            if (setNx(key, value, expireTimeMs, TimeUnit.MILLISECONDS)) {
                lockMapThreadLocal.get().put(key, value); // 记录锁
                return true;
            }

            try {
                TimeUnit.MILLISECONDS.sleep(intervalMs);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("获取锁被中断 key={}", key);
                return false;
            }
        }

        return false;
    }

    /**
     * 释放锁（不需要传 value）
     */
    public boolean unlock(String key) {
        Map<String, String> lockMap = lockMapThreadLocal.get();
        String value = lockMap.get(key);

        if (value == null) {
            log.warn("当前线程未持有锁，key={}", key);
            return false;
        }

        try {
            Object currentValue = redisTemplate.opsForValue().get(key);
            if (value.equals(currentValue)) {
                boolean deleted = Boolean.TRUE.equals(redisTemplate.delete(key));
                if (deleted) {
                    lockMap.remove(key);
                }
                return deleted;
            } else {
                log.warn("锁释放失败，key={}，当前值不匹配", key);
            }
        } catch (Exception e) {
            log.error("释放锁异常 key={} value={}", key, value, e);
        }

        return false;
    }

    /**
     * 清除线程上下文缓存（在任务结束或并发线程池中使用时必须调用）
     */
    public void clearThreadLockContext() {
        lockMapThreadLocal.remove();
    }

    /**
     * 设置分布式锁的原子操作
     */
    private Boolean setNx(String key, String value, Long expireTime, TimeUnit timeUnit) {
        if (key == null || value == null) return false;
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, timeUnit);
        } catch (Exception e) {
            log.error("执行 setNx 异常 key={} value={}", key, value, e);
            return false;
        }
    }

    public <T> void setHashObject(String key, T t){
        if (null != t) {
            Map<String, Object> fieldMap = JSON.parseObject(
                    JSON.toJSONString(t),
                    new TypeReference<Map<String, Object>>() {
                    }
            );
            redisTemplate.opsForHash().putAll(key, fieldMap);
        }
    }

    public <T> T getHashObject(String key, Class<T> clazz){
        Map<Object, Object> fieldMap = redisTemplate.opsForHash().entries(key);
        return JSON.parseObject(JSON.toJSONString(fieldMap), clazz);
    }
}
